﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace API.Core
{
    public static class Util
    {
        /// <summary>
        /// Генерация пароля
        /// </summary>
        /// <param name="passwordLength"></param>
        /// <param name="strongPassword"></param>
        /// <returns></returns>
        public static string PasswordGenerator(int passwordLength, bool strongPassword)
        {
            var random = new Random();

            int seed = random.Next(1, int.MaxValue);

            //const string allowedChars = "ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            const string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            const string specialCharacters = @"!#$%&'()*+,-./:;<=>?@[\]_";

            var chars = new char[passwordLength];
            var rd = new Random(seed);

            for (var i = 0; i < passwordLength; i++)
            {
                // If we are to use special characters
                if (strongPassword && i % random.Next(3, passwordLength) == 0)
                {
                    chars[i] = specialCharacters[rd.Next(0, specialCharacters.Length)];
                }
                else
                {
                    chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
                }
            }

            return new string(chars);
        }

        /// <summary>
        /// Получение хэша строки
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetMD5(string value)
        {
            byte[] data = System.Security.Cryptography.MD5
                .Create()
                .ComputeHash(System.Text.Encoding.UTF8.GetBytes(value));

            var sBuilder = new System.Text.StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }
    }
}